require 'net/ftp'
require 'tempfile'
require 'zlib'

require 'rubygems'
require 'bio'
require 'bio/db/pdb'

module Bio
end

class Bio::PDB
end

module Bio::PDB::Fetch
  def fetch(pdb_id)
    filename = 'pdb' + pdb_id.downcase + '.ent.gz'

    Net::FTP.open('ftp.wwpdb.org') do |ftp|
      ftp.login
      ftp.chdir('/pub/pdb/data/structures/all/pdb/')
      if ftp.nlst.include? filename
        # Send output to a temporary file then decompress
        temp = Tempfile.new(pdb_id)
        ftp.getbinaryfile('/pub/pdb/data/structures/all/pdb/' + filename,temp.path)
        Bio::PDB.new(Zlib::GzipReader.open(temp.path).read)
      else
        nil
      end
    end
  end
end

class Bio::PDB
  extend Bio::PDB::Fetch
end

